package com.isyscore.os.metadata.kettle.base;

import com.isyscore.os.metadata.enums.KettleDataFlowNodeType;
import com.isyscore.os.metadata.kettle.vis.VisNode;
import org.apache.commons.lang.time.DateUtils;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.errorhandling.StreamInterface;
import org.pentaho.di.trans.steps.filterrows.FilterRowsMeta;

import java.util.Date;
import java.util.List;

public abstract class AbstractStep implements Step{


    protected StepMeta getStep(TransMeta transMeta, String label) {
        List<StepMeta> list = transMeta.getSteps();
        for (int i = 0; i < list.size(); i++) {
            StepMeta step = list.get(i);
            if (label.equals(step.getName()))
                return step;
        }
        return null;
    }

    protected void updateStep(TransMeta transMeta, String label, StepMeta newStep) {
        List<StepMeta> list = transMeta.getSteps();
        for (int i = 0; i < list.size(); i++) {
            StepMeta step = list.get(i);
            if (label.equals(step.getName())){
                transMeta.removeStep(i);
                transMeta.addStep(newStep);
                }
        }
    }

    protected String getFiledType(List<ValueMetaInterface> list, String name){
        for (ValueMetaInterface valueMetaInterface : list) {
            if(valueMetaInterface.getName().equals(name)){
                return valueMetaInterface.getTypeDesc();
            }
        }
        return "";
    }

    protected Date isDate(String value){
        String[] parsePatterns = {"yyyy-MM-dd", "yyyy/MM/dd", "yyyyMMdd",
                "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
                "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyyMMdd HH:mm:ss"};

        if (value == null) {
            return null;
        }
        try {
            return  DateUtils.parseDate(value, parsePatterns);
        } catch (Exception e) {
//            throw new DataFactoryException(ErrorCode.IS_NOT_DATE,value);
            return null;
        }
    }

    protected void dealMultiOut(TransMeta transMeta, FlowConfig transGraph, String sortStepName, FlowHup transHup) {
        VisNode pr = transGraph.getNodeByName(transHup.getFrom());
        if(pr.isMultiOut()){
            StepMeta stepMeta = getStep(transMeta, transHup.getFrom());
            if(stepMeta.getTypeId().equals( KettleDataFlowNodeType.FilterRows.name())){
                FilterRowsMeta node = (FilterRowsMeta)stepMeta.getStepMetaInterface();
                List<StreamInterface> targetStreams = node.getStepIOMeta().getTargetStreams();
                targetStreams.get(0).setSubject(sortStepName);
            }
        }
    }
}
